package com.bub.pay.framework.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.bub.pay.framework.common.entity.model.RespObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import static com.bub.pay.framework.common.base.Cause.unlogin;

public class AuthcFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(AuthcFilter.class);


    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        if (isLoginRequest(request, response)) {
            //判断是否post请求
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                //去登录接口
                return true;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                response.getOutputStream().write(JSON.toJSONBytes(new RespObject("非法请求")));
                return false;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            response.getOutputStream().write(JSON.toJSONBytes(new RespObject(unlogin.getCode(), unlogin.getInfo())));
            return false;
        }
    }

}
